<!-- MessageList.vue -->
<template>
  <div class="message-list">
    <!-- 搜索框 -->
    <div class="search-box">
      <el-input
          v-model="searchText"
          placeholder="搜索聊天"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          @clear="clearSearch"
      />
    </div>

    <!-- 消息列表 -->
    <div class="message-items" v-loading="loading">
      <!-- 置顶会话 -->
      <div v-if="pinnedConversations.length > 0" class="pinned-section">
        <div class="section-title">置顶聊天</div>
        <div class="conversation-list">
          <div
              v-for="conversation in pinnedConversations"
              :key="conversation.id"
              class="conversation-item"
              :class="{
                'active': currentChat?.id === conversation.id,
                'unread': conversation.unreadCount > 0
              }"
              @click="selectConversation(conversation)"
          >
            <div class="conversation-avatar">
              <el-avatar
                  :size="48"
                  :src="getConversationAvatar(conversation)"
                  :shape="conversation.type === 'group' ? 'square' : 'circle'"
              >
                <el-icon v-if="conversation.type === 'group'"><User /></el-icon>
                <span v-else>{{ getConversationName(conversation)?.charAt(0) }}</span>
              </el-avatar>
              <!-- 未读消息小红点 -->
              <div v-if="conversation.unreadCount > 0" class="unread-badge">
                {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
              </div>
            </div>

            <div class="conversation-content">
              <div class="conversation-header">
                <div class="conversation-name">{{ getConversationName(conversation) }}</div>
                <div class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</div>
              </div>

              <div class="conversation-preview">
                <div class="last-message">
                  <span v-if="conversation.lastMessage">
                    <template v-if="conversation.lastMessage.sender">
                      <span v-if="conversation.type === 'group'" class="sender-name">
                        {{ conversation.lastMessage.sender.name }}:
                      </span>
                    </template>
                    {{ getMessagePreview(conversation.lastMessage) }}
                  </span>
                  <span v-else class="no-message">暂无消息</span>
                </div>

                <!-- 置顶标识 -->
                <el-icon class="pin-icon"><Star /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 普通会话 -->
      <div v-if="normalConversations.length > 0" class="normal-section">
        <div class="section-title">最近聊天</div>
        <div class="conversation-list">
          <div
              v-for="conversation in normalConversations"
              :key="conversation.id"
              class="conversation-item"
              :class="{
                'active': currentChat?.id === conversation.id,
                'unread': conversation.unreadCount > 0
              }"
              @click="selectConversation(conversation)"
          >
            <div class="conversation-avatar">
              <el-avatar
                  :size="48"
                  :src="getConversationAvatar(conversation)"
                  :shape="conversation.type === 'group' ? 'square' : 'circle'"
              >
                <el-icon v-if="conversation.type === 'group'"><User /></el-icon>
                <span v-else>{{ getConversationName(conversation)?.charAt(0) }}</span>
              </el-avatar>
              <!-- 未读消息小红点 -->
              <div v-if="conversation.unreadCount > 0" class="unread-badge">
                {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
              </div>
            </div>

            <div class="conversation-content">
              <div class="conversation-header">
                <div class="conversation-name">{{ getConversationName(conversation) }}</div>
                <div class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</div>
              </div>

              <div class="conversation-preview">
                <div class="last-message">
                  <span v-if="conversation.lastMessage">
                    <template v-if="conversation.lastMessage.sender">
                      <span v-if="conversation.type === 'group'" class="sender-name">
                        {{ conversation.lastMessage.sender.name }}:
                      </span>
                    </template>
                    {{ getMessagePreview(conversation.lastMessage) }}
                  </span>
                  <span v-else class="no-message">暂无消息</span>
                </div>

                <!-- 操作菜单 -->
                <el-dropdown
                    trigger="click"
                    @command="handleConversationCommand($event, conversation)"
                    class="conversation-menu"
                >
                  <el-icon class="menu-icon"><MoreFilled /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                          v-if="!conversation.pinned"
                          command="pin"
                          :icon="Star"
                      >
                        置顶聊天
                      </el-dropdown-item>
                      <el-dropdown-item
                          v-else
                          command="unpin"
                          :icon="StarFilled"
                      >
                        取消置顶
                      </el-dropdown-item>
                      <el-dropdown-item command="markRead" :icon="Check">
                        标记已读
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" :icon="Delete" divided>
                        删除聊天
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && conversations.length === 0" class="empty-state">
        <el-empty description="暂无聊天记录">
          <el-button type="primary" @click="goToContact">
            去通讯录开始聊天
          </el-button>
        </el-empty>
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMore && conversations.length > 0" class="load-more">
        <el-button
            type="text"
            @click="loadMore"
            :loading="loadingMore"
            class="load-more-btn"
        >
          加载更多
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, User, Star, StarFilled, MoreFilled, Check, Delete } from '@element-plus/icons-vue'
import { getChatConversations } from '@/api/teacher'

interface Conversation {
  id: number
  type: 'private' | 'group'
  title?: string
  avatar?: string
  pinned?: boolean
  unreadCount: number
  lastMessage?: {
    id: number
    content: string
    messageType: string
    sender?: {
      id: number
      name: string
      avatar?: string
    }
    createdAt: string
  }
  lastMessageTime: string
  // 私聊特有字段
  targetUser?: {
    id: number
    name: string
    avatar?: string
    role: string
  }
  // 群聊特有字段
  participantCount?: number
}

interface Props {
  currentChat?: any
}

interface Emits {
  (e: 'conversation-selected', conversation: any): void
  (e: 'switch-to-contact'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const searchText = ref('')
const conversations = ref<Conversation[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const currentPage = ref(0)
const hasMore = ref(true)
const pageSize = 20

// 计算属性
const pinnedConversations = computed(() => {
  return conversations.value.filter(conv => conv.pinned)
})

const normalConversations = computed(() => {
  return conversations.value.filter(conv => !conv.pinned)
})

// 生命周期
onMounted(() => {
  loadConversations()
})

// 加载会话列表
const loadConversations = async () => {
  try {
    loading.value = true
    const response = await getChatConversations(currentPage.value, pageSize)

    if (response.success) {
      const newConversations = response.data.content.map((conv: any) => ({
        id: conv.id,
        type: conv.type,
        title: conv.title,
        avatar: conv.avatar,
        pinned: conv.pinned || false,
        unreadCount: conv.unreadCount || 0,
        lastMessage: conv.lastMessage,
        lastMessageTime: conv.lastMessage?.createdAt || conv.updatedAt,
        targetUser: conv.targetUser,
        participantCount: conv.participantCount
      }))

      if (currentPage.value === 0) {
        conversations.value = newConversations
      } else {
        conversations.value = [...conversations.value, ...newConversations]
      }

      hasMore.value = !response.data.last
    } else {
      ElMessage.error('加载会话列表失败')
    }
  } catch (error) {
    console.error('加载会话列表失败:', error)
    ElMessage.error('加载会话列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (loadingMore.value || !hasMore.value) return

  loadingMore.value = true
  currentPage.value += 1
  await loadConversations()
}

// 搜索处理
const handleSearch = () => {
  // 这里可以实现实时搜索功能
  console.log('搜索关键词:', searchText.value)
  // 可以调用 searchConversations API
}

const clearSearch = () => {
  // 重置搜索，重新加载所有会话
  currentPage.value = 0
  loadConversations()
}

// 获取会话头像
const getConversationAvatar = (conversation: Conversation): string => {
  if (conversation.type === 'private') {
    return conversation.targetUser?.avatar || conversation.avatar || ''
  }
  return conversation.avatar || ''
}

// 获取会话名称
const getConversationName = (conversation: Conversation): string => {
  if (conversation.type === 'private') {
    return conversation.targetUser?.name || conversation.title || '未知用户'
  }
  return conversation.title || '未命名群聊'
}

// 获取消息预览
const getMessagePreview = (message: any): string => {
  if (!message) return ''

  const content = message.content || ''
  const messageType = message.messageType || 'text'

  switch (messageType) {
    case 'text':
      return content.length > 20 ? content.substring(0, 20) + '...' : content
    case 'image':
      return '[图片]'
    case 'file':
      return '[文件]'
    case 'voice':
      return '[语音]'
    default:
      return '[消息]'
  }
}

// 格式化时间显示
const formatTime = (timestamp: string): string => {
  if (!timestamp) return ''

  const date = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())

  const diffDays = Math.floor((today.getTime() - messageDate.getTime()) / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    // 今天
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  } else if (diffDays === 1) {
    // 昨天
    return '昨天'
  } else if (diffDays < 7) {
    // 一周内
    const weekdays = ['日', '一', '二', '三', '四', '五', '六']
    return `周${weekdays[date.getDay()]}`
  } else {
    // 更早
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit'
    })
  }
}

// 选择会话
const selectConversation = (conversation: Conversation) => {
  // 构建传递给聊天面板的数据
  const chatData = {
    ...conversation,
    name: getConversationName(conversation),
    avatar: getConversationAvatar(conversation)
  }

  emit('conversation-selected', chatData)
}

// 处理会话操作命令
const handleConversationCommand = async (command: string, conversation: Conversation) => {
  switch (command) {
    case 'pin':
      await pinConversation(conversation.id)
      break
    case 'unpin':
      await unpinConversation(conversation.id)
      break
    case 'markRead':
      await markConversationAsRead(conversation.id)
      break
    case 'delete':
      await deleteConversation(conversation)
      break
  }
}

// 置顶会话
const pinConversation = async (conversationId: number) => {
  try {
    // 调用置顶API
    // await pinConversationAPI(conversationId)
    ElMessage.success('已置顶聊天')
    // 重新加载会话列表
    await loadConversations()
  } catch (error) {
    ElMessage.error('置顶失败')
  }
}

// 取消置顶
const unpinConversation = async (conversationId: number) => {
  try {
    // 调用取消置顶API
    // await unpinConversationAPI(conversationId)
    ElMessage.success('已取消置顶')
    // 重新加载会话列表
    await loadConversations()
  } catch (error) {
    ElMessage.error('取消置顶失败')
  }
}

// 标记会话为已读
const markConversationAsRead = async (conversationId: number) => {
  try {
    // 调用标记已读API
    // await markMessagesAsReadAPI(conversationId)
    ElMessage.success('已标记为已读')
    // 重新加载会话列表
    await loadConversations()
  } catch (error) {
    ElMessage.error('标记已读失败')
  }
}

// 删除会话
const deleteConversation = async (conversation: Conversation) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除与"${getConversationName(conversation)}"的聊天记录吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 调用删除API
    // await deleteConversationAPI(conversation.id)
    ElMessage.success('删除成功')
    // 重新加载会话列表
    await loadConversations()
  } catch (error) {
    // 用户取消删除
    console.log('取消删除')
  }
}

// 跳转到通讯录
const goToContact = () => {
  emit('switch-to-contact')
}
</script>

<style scoped>
.message-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.search-box {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.message-items {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.section-title {
  padding: 12px 16px 8px;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  background: #fafafa;
}

.conversation-list {
  padding: 0;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.conversation-item:hover {
  background-color: #f5f7fa;
}

.conversation-item.active {
  background-color: #ecf5ff;
}

.conversation-item.unread .conversation-name {
  font-weight: 600;
}

.conversation-avatar {
  position: relative;
  margin-right: 12px;
  flex-shrink: 0;
}

.unread-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  min-width: 18px;
  height: 18px;
  font-size: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.conversation-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.conversation-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-time {
  font-size: 11px;
  color: #909399;
  flex-shrink: 0;
  margin-left: 8px;
}

.conversation-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  flex: 1;
  font-size: 13px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sender-name {
  color: #606266;
  margin-right: 4px;
}

.no-message {
  color: #c0c4cc;
  font-style: italic;
}

.pin-icon {
  color: #e6a23c;
  font-size: 14px;
  margin-left: 8px;
}

.conversation-menu {
  margin-left: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.conversation-item:hover .conversation-menu {
  opacity: 1;
}

.menu-icon {
  color: #c0c4cc;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
}

.menu-icon:hover {
  background-color: #f0f0f0;
  color: #606266;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px;
}

.load-more {
  padding: 16px;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.load-more-btn {
  width: 100%;
  color: #409eff;
}

/* 滚动条样式 */
.message-items::-webkit-scrollbar {
  width: 6px;
}

.message-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.message-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
